﻿/******************CRM.SanPham.cs********************\
 * Module name: Logic San Pham
 * Description: Business logic for San Pham
 * Author: viettp
\****************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OODCRM.Dialogs;
using Microsoft.Windows.Controls.Ribbon;
using OODCRM.Common;
using System.Windows;

namespace OODCRM
{
    public partial class MainWindow : RibbonWindow
    {

        internal void SanPham_NewExecuted()
        {
            dicDialogData[CRMDialog.ThemSanPham] = new SANPHAM();

            dicDialogMode[CRMDialog.ThemSanPham] = DialogMode.Them;

            EnableDialog(CRMDialog.ThemSanPham);
        }

        internal void SanPham_EditExecuted()
        {
            SANPHAM item = dgrSanPham.SelectedItem as SANPHAM;
            if (item == null) return;

            dicDialogData[CRMDialog.ThemSanPham] = item;

            dicDialogMode[CRMDialog.ThemSanPham] = DialogMode.Sua;

            EnableDialog(CRMDialog.ThemSanPham);
        }

        internal void SanPham_DeleteExecuted()
        {
            SANPHAM item = dgrSanPham.SelectedItem as SANPHAM;
            if (item == null) return;

            // Check FK before delete
            var x1 = dataContext.CHITIETSANPHAMCOHOIs.FirstOrDefault(x => x.MaSanPham == item.MaSanPham) as CHITIETSANPHAMCOHOI;
            if (x1 != null)
            {
                MessageBox.Show("Tồn tại chi tiết sản phẩm tham gia trong phân tích 1 cơ hội khác! (" + x1.MaSanPham + ")",
                    "Không thể xoá", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // Confirm and delete
            if (MessageBox.Show(
                    "Bạn có chắc muốn xoá sản phẩm \"" + item.TenSanPham + "\" ?", "Xác nhận xoá",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question
                    )
                    == MessageBoxResult.Yes)
            {
                listSanPham.Remove(item);
                dataContext.SANPHAMs.DeleteOnSubmit(item);
                try
                {
                    dataContext.SubmitChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}
